package com.duan.laugh.test.mongo.controller;

import cn.hutool.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Random;

/**
 * @author duanjw
 */
@RestController
@RequestMapping
public class MongoController {
    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping("/{id}")
    public boolean insert(@PathVariable String id, @RequestBody Map map) {
        final JSONObject jsonObject = new JSONObject(map);
        mongoTemplate.insert(jsonObject,id);
        return true;
    }
    @GetMapping("/{id}")
    public Object find(@PathVariable String id){
        JSONObject ans = mongoTemplate
                .findOne(new Query(), JSONObject.class,
                        id);
        return ans;
    }

    @GetMapping
    public Object test(){
        final String collectionName = "person";


        for (int i = 0; i < 10000; i++) {
            JSONObject object = new JSONObject();
            for (int j = 0; j < 1100; j++) {
                object.put("name" + j, "我是随机数"+ new Random().nextFloat());
            }
            mongoTemplate.insert(object,collectionName);
        }


        JSONObject ans = mongoTemplate
                .findOne(new Query(Criteria.where("name").is("哈哈")), JSONObject.class,
                        collectionName);
        System.out.println(ans);
        return null;
    }
}
